<!DOCTYPE html>
<html>
  <head>
    <title>geoHash</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
  <div id="allmap" style="width:100%;height:600px;"></div>

  <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>
  <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=EIbNEi0OaRxzjc0gqy3YQnNk"></script>
  <script type="text/javascript">

    var map = new BMap.Map("allmap");
    var point = new BMap.Point(116.331398,39.897445);
    map.centerAndZoom(point,15);

    var navigationControl = new BMap.NavigationControl({
      anchor: BMAP_ANCHOR_TOP_LEFT,
      type: BMAP_NAVIGATION_CONTROL_LARGE,
      enableGeolocation: true
    });
    map.addControl(navigationControl);

    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function(r){
      if(this.getStatus() == BMAP_STATUS_SUCCESS){
        var mk = new BMap.Marker(r.point);
        map.addOverlay(mk);
        map.panTo(r.point);
        mk.setAnimation(BMAP_ANIMATION_BOUNCE);

        getRestaurants(encode_geohash(r.point.lat, r.point.lng, 12))
      }
      else {
        alert('failed'+this.getStatus());
      }
    },{enableHighAccuracy: true})

    function addClickHandler(title,content,marker){
      marker.addEventListener("click",function(e){
                openInfo(title,content,e)}
      );
    }

    function openInfo(title,content,e){
      var opts = {
        width : 250,
        height: 120,
        title : title ,
        enableMessage:false
      };

      var p = e.target;
      var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
      var infoWindow = new BMap.InfoWindow(content,opts);  // 创建信息窗口对象
      map.openInfoWindow(infoWindow,point); //开启信息窗口
    }

    var convertor = new BMap.Convertor();
    function getRestaurants(geohash){
      $.get("/restaurants/" + geohash + "/0/200",{},function(json){
        var restaurants = JSON.parse(json);
        var len = restaurants.length;

        var x = null;
        for(var i = 0; i < len; i++){

            x = restaurants[i];
            var ggPoint = new BMap.Point(x["longitude"],x["latitude"]);
            var pointArr = [];
            pointArr.push(ggPoint);

          (function(val){
            convertor.translate(pointArr, 1, 5,function(data){
              if(data.status === 0) {
                var marker = new BMap.Marker(data.points[0]);
                var title = val["name"];
                var content =   val["description"] + "<img style='float:right;width:80px;height:60px;' src='http://fuss10.elemecdn.com/"
                        + val["image_path"] + "'/>"+ "<br>电话："
                        + val["phone"] +"<br>营业时间"
                        + val["opening_hours"] +"<br>地址"
                        + val["address"] ;
                map.addOverlay(marker);
                addClickHandler(title,content,marker);
              }

            });
          })(x)
        }
      },"json")
    }


    function encode_geohash(latitude, longitude, deep) {
      var BASE32 = '0123456789bcdefghjkmnpqrstuvwxyz';
      var bits = [16, 8, 4, 2, 1];
      var lat = [-90.0, 90.0];
      var lon = [-180.0, 180.0];

      var bit = ch = i = 0;
      var is_even = 1;

      var i = 0;
      var mid;
      var geohash = '';
      while (i < deep) {
        if (is_even) {
          mid = (lon[0] + lon[1]) / 2;
          if (longitude > mid) {
            ch |= bits[bit];
            lon[0] = mid;
          } else {
            lon[1] = mid;
          }
        } else {
          mid = (lat[0] + lat[1]) / 2;
          if (latitude > mid) {
            ch |= bits[bit];
            lat[0] = mid;
          } else {
            lat[1] = mid;
          }
        }

        is_even = !is_even;
        if (bit < 4)
          bit++;
        else {
          i++;
          geohash += BASE32[ch];
          bit = 0;
          ch = 0;
        }
      }
      return geohash;
    }

  </script>
  </body>
</html>
